package ru.urfc.portal.ui.client.googlets.client;

import ru.urfc.portal.ui.client.BaseGooglet;
import ru.urfc.portal.ui.client.Style;
import ru.urfc.portal.ui.client.controllers.BaseController;
import ru.urfc.portal.ui.client.controllers.ItemsController;
import ru.urfc.portal.ui.client.controllers.SimpleItemsController;
import ru.urfc.portal.ui.client.controllers.events.DeleteEvent;
import ru.urfc.portal.ui.client.controllers.events.PutEvent;
import ru.urfc.portal.ui.client.descriptor.GridDescriptor;

import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.shared.GwtEvent.Type;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Widget;

public class AssociatedUserEdit extends BaseGooglet {

	interface Binder extends UiBinder<Widget, AssociatedUserEdit> {}
	private static Binder binder = GWT.create(Binder.class);
	
	@UiField Style style;
	@UiField Element name;
	@UiField AnchorElement email;
//	@UiField Element phone;
	@UiField ComboBox<ModelData> userRole;
	@UiField ComboBox<ModelData> userState;

	public Type<ItemsController> SAVE = new Type<ItemsController>();

	@UiHandler("save")
	void save(ClickEvent e) {
		getEventsDispatcher().fireEvent(new PutEvent(SAVE));
	}

	public Type<BaseController> DELETE = new Type<BaseController>();

	@UiHandler("delete")
	void delete(ClickEvent e) {
		getEventsDispatcher().fireEvent(new DeleteEvent(DELETE));
	}
	
	@Override
	protected void init() {
		initWidget(binder.createAndBindUi(this));
		initCombobox("text", "code", null, userRole, USER_ROLE, CATALOGS, USER_ROLES);
		initCombobox("text", "code", null, userState, USER_STATE, CATALOGS, USER_STATES);
		
		GridDescriptor descriptor = new GridDescriptor(USER, CLIENTS, getClientId(), CLIENT_ASSOCIATED_USERS, getItemId());
		descriptor.addCompositeField("firstName", "middleName", "lastName").assign(name, " ");
		descriptor.addAnchorFields("email", "email", "mailto:{0}", email, email);
//		descriptor.addTextField("phone", phone);
		descriptor.addSelectField("role/code", userRole);
		descriptor.addSelectField("state/code", userState);
		
		createController(descriptor);// TODO megre contorllers
		register(SAVE, new SimpleItemsController(descriptor) {
			@Override
			public void onUpdate(Object data) {
				showMessage("Данные успешно сохранены");
			}
		});
		register(DELETE, new SimpleItemsController(descriptor) { 
			@Override
			public void onUpdate(Object data) {
				if (data.equals(HTTP_NO_CONTENT)) {
					redirect(PAGE_ASSOCIATED_USERS);
				}
			}
		});
	}

}